package com.sl.au.controller;

import java.io.UnsupportedEncodingException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.sl.au.entity.Attachment;
import com.sl.au.entity.Module;
import com.sl.au.entity.Section;
import com.sl.au.entity.User;
import com.sl.au.repository.WeeklyRepository;
import com.sl.au.service.AttachmentService;

import com.sl.au.service.OperateLogService;
import com.sl.au.service.SectionService;
import com.sl.au.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Account;
import com.sl.au.entity.Weekly;
import com.sl.au.entity.WholeSetDevice;
import com.sl.au.service.ExcelService;
import com.sl.au.service.WeeklyService;

@RestController
@RequestMapping(value = "/ui/weekly")
public class WeeklyController extends BaseController {

	@Autowired
	WeeklyService weeklyService;
	@Autowired
	ExcelService excelService;
	@Autowired
	AttachmentService attachmentService;
	@Autowired
	OperateLogService operateLogService;
	
	@Autowired
	SectionService sectionService;
	
	@Autowired
	UserService userService;

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView modelAndView = createLayoutView("weekly/weeklyindex1");
		String name="weeklyMng";
		Boolean canInstruct=true;//可批示（本人为false）
		Module module = this.getPageModule(name);
		String dataFilter=module.getDataFilter();
		if(dataFilter.equals("本人")) canInstruct=false;
		modelAndView.addObject("module", module);
		modelAndView.addObject("canInstruct", canInstruct);
		return modelAndView;
	}
	

	/**周报列表
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getpage2", method = RequestMethod.GET)
	public Map<String, Object> getPage2(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String,String> condition= new HashMap<>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		String isInstructions = request.getParameter("isInstructions");
		
		if(key==null){
			key="";
		}
		List<Weekly> Weeklys = null;
		Module module = this.getPageModule("weeklyMng");
		String dataFilter=module.getDataFilter();
		Account a = this.getMyAccount();
		String userId=null;
		String superior=null;
		String areaId=null;
		String sectionId=null;
		if(a!=null){
			userId=a.getUser().getId();
			superior = a.getUser().getSaleArea().getSuperior();
			areaId=a.getUser().getSaleArea().getId();
			Section s=sectionService.getRepository().findByChief(a.getUser());
			if(s!=null){
				sectionId=s.getId();
			}
		}
		condition.put("key", key);
		condition.put("userId", userId);
		condition.put("superior", superior);
		condition.put("areaId", areaId);
		condition.put("sectionId", sectionId);
		condition.put("isInstructions", isInstructions);
		Weeklys = weeklyService.getPage(start, length,condition,key,dataFilter,  "issueDate", Sort.Direction.DESC);
		long count=weeklyService.getCount(start, length, condition, dataFilter);
		map.put("data", Weeklys);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	/**移动端 获取周报列表
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getPageToMobile", method = RequestMethod.GET)
	public Map<String, Object> getPageToMobile(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String,String> condition= new HashMap<>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		boolean published=Boolean.valueOf(request.getParameter("published"));
		String key = request.getParameter("key");
		if(key==null){
			key="";
		}
		List<Weekly> Weeklys = null;
		Module module = this.getPageModule("weeklyMng");
		String dataFilter=module.getDataFilter();
		Account a = this.getMyAccount();
		String userId=null;
		String superior=null;
		String areaId=null;
		String sectionId=null;
		if(a!=null){
			userId=a.getUser().getId();
			superior = a.getUser().getSaleArea().getSuperior();
			areaId=a.getUser().getSaleArea().getId();
			Section s=sectionService.getRepository().findByChief(a.getUser());
			if(s!=null){
				sectionId=s.getId();
			}
		}
		condition.put("key", key);
		condition.put("userId", userId);
		condition.put("superior", superior);
		condition.put("areaId", areaId);
		condition.put("sectionId", sectionId);
		Weeklys = weeklyService.getPageToMobile(start, length,condition,key,dataFilter,published,  "issueDate", Sort.Direction.DESC);
        long count=weeklyService.getCountMobile(start, length, condition, dataFilter,published);
		map.put("data", Weeklys);
		map.put("recordsTotal", count);
		return map;
	}
	/**
	 * 增加一个周报 
	 */
	@RequestMapping( method = RequestMethod.PUT)
	public Map<String, Object> putWeekly(@RequestBody Weekly weekly) {
		Map<String, Object> map = new HashMap<String, Object>();
		Account a = this.getMyAccount();
		User user =new User();
		if(a!=null){
			user = a.getUser();
			weekly.setIssuer(user);
			weekly.setIsInstructions("未提交");
			weekly.setIssuerName(user.getEmpLogin().getUserName());
		}else{
			user=weekly.getIssuer();
		}
		//移动端使用
		if(weekly.isPublished()){
			weekly.setIsInstructions("已提交");
			weekly.setPublished(true);
			weekly.setIssueDate(new Date());
		}
		
		
        int code=-1;
        if(!StringUtils.hasText(weekly.getId())) weekly.setId(java.util.UUID.randomUUID().toString());
	    weeklyService.getRepository().save(weekly);
	    code=0;
		String content  = "新增周报【" + weekly.getName() + "】";
	    operateLogService.log(user, "新增周报", content);
		String weeklyId = weekly.getId();
		Date createTime = weekly.getCreateTime();
		map.put("code", code);
		map.put("id", weekly.getId());
		map.put("weeklyId", weeklyId);
		map.put("createTime", createTime);
		return map;
	}
//	/**
//	 * 查找当前用户的周报
//	 */
//	@RequestMapping(value="myweeklies", method = RequestMethod.GET)
//	public Map<String, Object> getMyweeklies(HttpServletRequest request) {
//		Map<String, Object> map = new HashMap<String, Object>();
//		int start = Integer.parseInt(request.getParameter("start"));
//		int length = Integer.parseInt(request.getParameter("length"));
//		String key = request.getParameter("key");
//		String issuerId = request.getParameter("issuerId");
//		List<Weekly> Weeklys = null;
//		Weeklys = weeklyService.getPageMyWeeklies(issuerId,start, length, key, "issueDate", Sort.Direction.DESC);
//		Account a = this.getMyAccount();
//		String userId=a.getUser().getId();
//		long count = weeklyService.getRepository().getCount(key,userId);
//		map.put("data", Weeklys);
//		map.put("draw", request.getParameter("draw"));
//		map.put("recordsFiltered", count);
//		map.put("recordsTotal", count);
//		return map;
//	}
	/**
	 * 提交一个周报
	 */
	@RequestMapping( value="/submit",method = RequestMethod.POST)
	public Map<String, Object> submithWeekly(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String weeklyId = request.getParameter("weeklyId");
		Weekly weekly  = weeklyService.getRepository().findOne(weeklyId);
		weekly.setIsInstructions("已提交");
		weekly.setPublished(true);
		weekly.setIssueDate(new Date());
		weeklyService.getRepository().save(weekly);
		Account a = this.getMyAccount();
		User user = a.getUser();
//		weekly.setIssuer(user);
		Weekly old=weeklyService.getRepository().findOne(weekly.getId());
		if(old!=null){
			String content  = "提交周报【" + weekly.getName() + "】";
			operateLogService.log(user, "提交周报", content);
		}
		Date updateTime= weekly.getUpdateTime();
		map.put("weeklyId", weeklyId);
		map.put("updateTime",updateTime);
		return map;
	}
	
	/**编辑保存周报
	 * @param weekly
	 * @return
	 */
	@RequestMapping(method = RequestMethod.PATCH)
	public Map<String, Object> patchWeekly(@RequestBody Weekly weekly) {
		Map<String, Object> map = new HashMap<String, Object>();
		int code=-1;
		if(weekly.getInstruction()!=null&&!weekly.getInstruction().equals("")){
			weekly.setIsInstructions("已批示");
		}else{
			weekly.setIsInstructions("未提交");
		}
		weeklyService.patch(weekly);
		code=0;
		map.put("code", code);
		return map;
	}


	/**mobile使用
	 * 删除一个周报 
	 */
	@RequestMapping(value="{id}", method = RequestMethod.DELETE)
	public Map<String, Object> deleteWeekly(@PathVariable String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		int code=-1;
		weeklyService.getRepository().delete(id);
		code=0;
		map.put("code", code);
		return map;
	}
	@RequestMapping(value = "/delWeekly", method = RequestMethod.GET)
	public Map<String, Object> delWeekly(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		String id[] = ids.split(",");
		List<Weekly> weeklies = new ArrayList<Weekly>();
		for (int i = 0; i < id.length; i++) {
			String weeklyId = id[i];
			Weekly weekly = new Weekly();
			weekly.setId(weeklyId);
			weeklies.add(weekly);
			List<Attachment> attachments = new ArrayList<Attachment>();
			attachments = attachmentService.getRepository().findByParentId(weeklyId);
			attachmentService.getRepository().deleteInBatch(attachments);
		}
		/////插入删除日志
		Account a = this.getMyAccount();
		User user = a.getUser();
		for(Weekly d:weeklies){
			Weekly old=weeklyService.getRepository().findOne(d.getId());
			String content  = "删除周报【" + old.getName() + "】";
			operateLogService.log(user, "删除周报", content);
		}
		weeklyService.getRepository().deleteInBatch(weeklies);

		map.put("code", 0);
		return map;
	}
	
	/**验证是否是当前登陆人的周报
	 * @param userId
	 * @return
	 */
	@RequestMapping(value="/validate/{userId}",method=RequestMethod.GET)
	public Map<String, Object>codeValidate(@PathVariable String userId){
		Map<String, Object>map=new HashMap<String,Object>();
		Account a = this.getMyAccount();
		int code=1;
		if (a.getUser().getId().equals(userId)) {
			code=0;
		}
		map.put("code", code);
		return map;
		
	}
	/**将查询结果导出成EXCEL
	 * 
	 * @param key搜索内容
	 */
	@RequestMapping(value = "export/{key}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<Resource> excelFile(@PathVariable String key,HttpServletRequest request) throws UnsupportedEncodingException {
		if(key.equals("null")) key="";
		Map<String,String> condition= new HashMap<>();
		Account a = this.getMyAccount();
		Module module = this.getPageModule("weeklyMng");
		String dataFilter=module.getDataFilter();
		String userId=null;
		String superior=null;
		String areaId=null;
		if(a!=null){
			userId=a.getUser().getId();
			superior = a.getUser().getSaleArea().getSuperior();
			areaId=a.getUser().getSaleArea().getId();
		}
		condition.put("key", key);
		condition.put("userId", userId);
		condition.put("superior", superior);
		condition.put("areaId", areaId);
		List<Weekly> result=weeklyService.getPage(0, Integer.MAX_VALUE,condition,key,dataFilter,  "issueDate", Sort.Direction.DESC);;
		return this.excelService.toExcel(result, "周报.xlsx");
	}
	///导出选择项
		@RequestMapping(value = "/exportSelects/{key}", method = RequestMethod.GET)
		@ResponseBody
		public ResponseEntity<Resource> exportSelects(@PathVariable String key, HttpServletRequest request)
						throws UnsupportedEncodingException {	
			String id[] = key.split(",");
			List<Weekly> result = new ArrayList<Weekly>();
			for (int i = 0; i < id.length; i++) {
				String weekId = id[i];
				Weekly d=weeklyService.getRepository().findOne(weekId);
				result.add(d);
			}
			return this.excelService.toExcel(result, "周报.xlsx");
		}
}
